package com.practice.handler;

import cn.hutool.core.util.StrUtil;
import com.practice.response.ResponseR;
import com.practice.exception.ServiceException;
import com.practice.util.ResponseRUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * 全局异常处理器
 */
@Order(Ordered.HIGHEST_PRECEDENCE)
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseR<Void> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                               HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        return ResponseRUtil.error(e.getMessage());
    }

    @ExceptionHandler(StackOverflowError.class)
    public ResponseR<?> handleStackOverflow(StackOverflowError ex) {
        log.error("检测到栈溢出: {}", ex.getMessage());
        return ResponseRUtil.error("服务内部错误,检测到栈溢出");
    }


    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public ResponseR<Void> handleServiceException(ServiceException e,
                                                  HttpServletRequest request) {
        return ResponseRUtil.error(e.getMessage());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public ResponseR<Void> handleBindException(BindException e) {
        String message = e.getAllErrors().stream()
            .map(DefaultMessageSourceResolvable::getDefaultMessage)
            .collect(Collectors.joining(", "));
        return ResponseRUtil.error(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseR<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return ResponseRUtil.error(message);
    }

    /**
     * 数据校验异常
     */
    @ExceptionHandler(ValidationException.class)
    public ResponseR<Void> handleValidationException(ValidationException e) {
        return ResponseRUtil.error(e.getMessage());
    }

    @ExceptionHandler(NullPointerException.class)
    public ResponseR<Void> handleNullPointerException(NullPointerException e) {

        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
            throw e;
        }

        return ResponseRUtil.error("空指针异常(null), 请联系管理员!");
    }

    /**
     * 拦截非法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseR<Void> handleIllegalArgumentException(IllegalArgumentException e) {

        String message = StrUtil.isNotBlank(e.getMessage())
                ? e.getMessage()
                : e.toString();


        return ResponseRUtil.error(e.getMessage());
    }

    /**
     * 拦截参数转换异常
     */
    @ExceptionHandler(HttpMessageConversionException.class)
    public ResponseR<Void> httpMessageConversionException(HttpMessageConversionException e) {
        String message = "系统异常(参数转换异常), 请联系管理员!";
        Throwable cause = e.getCause();
        if (cause != null) {
            Throwable customCause = cause.getCause();
            if (customCause instanceof ServiceException) {
                message = customCause.getMessage();
            }
        }



        return ResponseRUtil.error(message);
    }



    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseR<Void> handleRuntimeException(RuntimeException e) {

        String message = StrUtil.isNotBlank(e.getMessage())
                ? e.getMessage()
                : e.toString();

        log.error("运行时异常",e);

        return ResponseRUtil.error("运行时异常, 请联系管理员!");
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseR<Void> handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        String message = StrUtil.isNotBlank(e.getMessage())
                ? e.getMessage()
                : e.toString();

        log.error("系统异常",e);

        return ResponseRUtil.error("系统异常, 请联系管理员!");
    }


}
